// information/jjkPoste/index.js
const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    createUid: 0,
    staffId: 0,
    cardItemId: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var windowWidth = wx.getSystemInfoSync().windowWidth * 0.96;
    var canvasHeight = windowWidth * 1.33;
    this.setData({
      userId: options.userId,
      windowWidth: windowWidth,
      canvasHeight: canvasHeight
    })
    this.getCardItem(options.userId, options.staffId);
  },

  getCardItem: function (userId, staffId) {
    let that = this;
    wx.request({
      url: app.globalData.host + '/api/coupon/getCardItemByType',
      success: function (res) {
        if (res.data.Code == 0) {
          that.data.createUid = userId;
          that.data.staffId = staffId;
          that.data.cardItemId = res.data.Data.Id;
          that.getWxaCodeFile(userId, staffId, res.data.Data.Id);
        }
      }, fail: function (err) {
        that.data.createUid = userId;
        that.data.staffId = staffId;
        that.getWxaCodeFile(userId, staffId, 0);
      }
    })
  },

  //扫码领取玖玖卡（不限张数）
  getWxaCodeFile: function (userId, staffId, cardItemId) {
    let that = this;
    wx.showLoading({
      title: '生成中...',
      mask: true,
    })
    // let path = '/information/autoReceJJK/index?id=' + staffId + '&cardItemId=' + cardItemId + '&createUid=' + userId + '&timestamp=0&source=0';
    let path = 'information/autoReceJJK/index?t=4&p=' + staffId + '#' + cardItemId + '#' + userId + '#0#0';
    wx.request({
      url: app.globalData.host + "/api/Store/GetWxaCodeFile",
      data: {
        storeId: app.globalData.storeId,
        path: path,
        storeappid: app.globalData.storeAppId
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.Code == 0) {
          if (res.data.Data) {
            wx.downloadFile({
              url: 'https://static.711688.net.cn/upload/user/' + res.data.Data,
              success: function (res) {
                if (res.statusCode === 200) {
                  var codeSrc = res.tempFilePath;
                  that.getBgimg(codeSrc);
                } else {
                  wx.showToast({
                    title: '二维码下载失败！',
                    icon: 'none',
                    duration: 2000,
                    success: function () {
                      var codeSrc = "";
                      that.getBgimg(codeSrc);
                    }
                  })
                }
              }
            })
          } else {
            var codeSrc = "";
            that.getBgimg(codeSrc);
          }
        }
      },
    })
  },

  getBgimg: function (codeSrc) {
    let that = this;
    let bgUrl = 'https://static.711688.net.cn/upload/card/source/ua_2012111559452509321.png';
    wx.downloadFile({
      url: bgUrl,
      success: function (res) {
        if (res.statusCode === 200) {
          var bgImg = res.tempFilePath;
          that.sharePosteCanvasJJK(codeSrc, bgImg);
        } else {
          wx.showToast({
            title: '图片下载失败！',
            icon: 'none',
            duration: 2000
          })
        }
      }
    })
  },

  sharePosteCanvasJJK: function (codeSrc, bgImg) {
    let that = this;
    that.setData({
      showpost: true
    })
    const ctx = wx.createCanvasContext('myCanvas', that);
    const query = wx.createSelectorQuery().in(this);
    query.select('#canvas-container').boundingClientRect(function (rect) {
      var height = rect.height;
      var width = rect.width;

      ctx.drawImage(bgImg, 0, 0, width, height);

      let codeWidth = width * 150 / 340;
      ctx.fillStyle = '#ffffff';
      ctx.fillRect((width - codeWidth) / 2, width * 74 / 340, codeWidth, codeWidth)

      if (codeSrc) {
        ctx.drawImage(codeSrc, (width - codeWidth) / 2 + 5, width * 74 / 340 + 5, width * 140 / 340, width * 140 / 340);
      }
      ctx.font = '14px sans-serif';
      ctx.fillStyle = 'rgba(0, 0, 0, 1)';
      ctx.setTextAlign('center');
      ctx.fillText('微信扫码 免费领卡', width / 2, width * 224 / 340 + 20);
    }).exec()
    setTimeout(function () {
      ctx.draw();
      wx.hideLoading();
    }, 1000)
  },
  //点击保存到相册
  saveShareImg: function () {
    var that = this;
    wx.showLoading({
      title: '正在保存',
      mask: true,
    })
    setTimeout(function () {
      wx.canvasToTempFilePath({
        canvasId: 'myCanvas',
        success: function (res) {
          wx.hideLoading();
          var tempFilePath = res.tempFilePath;
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success(res) {
              wx.showModal({
                content: '图片已保存到相册，赶紧晒一下吧~',
                showCancel: false,
                confirmText: '好的',
                confirmColor: '#333',
                success: function (res) {
                  if (res.confirm) { }
                },
                fail: function (res) {
                }
              })
            },
            fail: function (res) {
              wx.showToast({
                title: '请删掉小程序再重新授权允许保存至相册',
                icon: 'none',
                duration: 2000
              })
            }
          })
        },
        fail: function (err) {
        }
      }, that);
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  // 测试
  /**
   * 用户点击右上角分享
   */
  // onShareAppMessage: function () {
  //   let that = this;
  //   let path = '/information/autoReceJJK/index?id=' + that.data.staffId + '&cardItemId=' + that.data.cardItemId + '&createUid=' + that.data.createUid + '&timestamp=0&source=0';
  //   return {
  //     title: '玖玖卡自动领取',
  //     path: path,
  //     success: function (res) {
  //       wx.showModal({
  //         title: '提示',
  //         content: '转发成功',
  //         showCancel: false
  //       })
  //     }
  //   }
  // }
})